package com.zhihaihe.file.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.qiwenshare.common.anno.MyLog;
import com.qiwenshare.common.exception.NotLoginException;
import com.qiwenshare.common.result.RestResult;
import com.zhihaihe.file.advice.CommonException;
import com.zhihaihe.file.commponent.FileDealComp;
import com.zhihaihe.file.dto.file.*;
import com.zhihaihe.file.pojo.TreeNode;
import com.zhihaihe.file.pojo.UserBean;
import com.zhihaihe.file.pojo.UserFileBean;
import com.zhihaihe.file.service.IFileService;
import com.zhihaihe.file.service.IUserFileService;
import com.zhihaihe.file.service.IUserService;
import com.zhihaihe.file.util.*;
import com.zhihaihe.file.vo.file.FileListVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.*;

/**
 *文件接口，主要用来做一些文件的基本操作，如创建目录，删除，移动，复制等
 * @author
 */
@RestController
@Slf4j
@RequestMapping("/file")
public class FileController {
    @Resource
    private IFileService fileService;
    @Resource
    private IUserService userService;
    @Resource
    private IUserFileService userFileService;

    @Resource
    private FileDealComp fileDealComp;
    /**
     * 创建目录（文件夹）
     * @param createFileDto
     * @return
     */
    @RequestMapping(value = "/createfile", method = RequestMethod.POST)
    @ResponseBody
    public R createFile(@Valid @RequestBody CreateFileDTO createFileDto) {
        UserBean sessionUserBean = (UserBean) SessionUtil.getSession();
        boolean isDirExist = userFileService.isDirExist(createFileDto.getFileName(), createFileDto.getFilePath(), sessionUserBean.getUserId());
        if (isDirExist) {
            return R.fail("同名文件已存在!");
        }
        UserFileBean userFile = new UserFileBean();
        userFile.setUserId(sessionUserBean.getUserId());
        userFile.setFileName(createFileDto.getFileName());
        userFile.setFilePath(createFileDto.getFilePath());
        userFile.setDeleteFlag(0);
        userFile.setIsDir(1);
        userFile.setUploadTime(DateUtil.getCurrentTime());
        userFileService.save(userFile);
        return R.success(null);
    }

    /**
     * 文件重命名
     * @param renameFileDto
     * @return
     */
    @RequestMapping(value = "/renamefile", method = RequestMethod.POST)
    @ResponseBody
    public R renameFile(@RequestBody RenameFileDTO renameFileDto) {
        UserBean sessionUserBean = (UserBean) SessionUtil.getSession();
        if (sessionUserBean == null) {
            throw new CommonException(ResultCodeEnum.NOT_LOGIN_ERROR);
        }
        UserFileBean userFile = userFileService.getById(renameFileDto.getUserFileId());

        List<UserFileBean> userFiles = userFileService.selectUserFileByNameAndPath(renameFileDto.getFileName(), userFile.getFilePath(), sessionUserBean.getUserId());
        if (userFiles != null && !userFiles.isEmpty()) {
            return R.fail("同名文件已存在");
        }

        LambdaUpdateWrapper<UserFileBean> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.set(UserFileBean::getFileName, renameFileDto.getFileName())
                .set(UserFileBean::getUploadTime, DateUtil.getCurrentTime())
                .eq(UserFileBean::getUserFileId, renameFileDto.getUserFileId());
        userFileService.update(lambdaUpdateWrapper);
        if (1 == userFile.getIsDir()) {
            userFileService.replaceUserFilePath(userFile.getFilePath() + renameFileDto.getFileName() + "/",
                    userFile.getFilePath() + userFile.getFileName() + "/", sessionUserBean.getUserId());
        }
        return R.success(null);
    }

    /**
     * 获取文件列表
     * @param filePath 文件路径
     * @param currentPage 当前页
     * @param pageCount 页面数量
     * @return
     */
    @RequestMapping(value = "/getfilelist", method = RequestMethod.GET)
    @ResponseBody
    public R getFileList(
            String filePath, long currentPage,long pageCount){

        UserFileBean userFile = new UserFileBean();
        UserBean sessionUserBean = (UserBean) SessionUtil.getSession();
        if (sessionUserBean == null) {
            throw new CommonException(ResultCodeEnum.NOT_LOGIN_ERROR);
        }
        if (userFile == null) {
            return R.fail(ResultCodeEnum.REQUEST_TIMEOUT.getMessage());

        }
        userFile.setUserId(sessionUserBean.getUserId());
        List<FileListVo> fileList;
        userFile.setFilePath(UFOPUtils.urlDecode(filePath));
        if (currentPage == 0 || pageCount == 0) {
            fileList = userFileService.userFileList(userFile, 0L, 10L);
        } else {
            long beginCount = (currentPage - 1) * pageCount;
            fileList = userFileService.userFileList(userFile, beginCount, pageCount);
        }

        LambdaQueryWrapper<UserFileBean> userFileLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userFileLambdaQueryWrapper.eq(UserFileBean::getUserId, userFile.getUserId())
                .eq(UserFileBean::getFilePath, userFile.getFilePath())
                .eq(UserFileBean::getDeleteFlag, 0);
        int total = userFileService.count(userFileLambdaQueryWrapper);

        Map<String, Object> map = new HashMap<>();
        map.put("total", total);
        map.put("list", fileList);
        return R.success(map);
    }

    /**
     * 批量删除文件
     * @param batchDeleteFileDto
     * @return
     */
    @PostMapping( "/batchdeletefile")
    @ResponseBody
    public R deleteImageByIds(@RequestBody BatchDeleteFileDTO batchDeleteFileDto) {
        UserBean sessionUserBean = (UserBean) SessionUtil.getSession();
        if (sessionUserBean == null) {
            throw new CommonException(ResultCodeEnum.NOT_LOGIN_ERROR);
        }
        //用户文件id如果不存在的话或出现空指针
        List<UserFileBean> userFiles = JSON.parseArray(batchDeleteFileDto.getFiles(), UserFileBean.class);
        DigestUtils.md5Hex("data");
        for (UserFileBean userFile : userFiles) {
            userFileService.deleteUserFile(userFile.getUserFileId(),sessionUserBean.getUserId());
        }
        return R.success("批量删除文件成功");
    }


    /**
     * 可以删除文件或者目录
     * @param deleteFileDto
     * @return
     */
    @RequestMapping(value = "/deletefile", method = RequestMethod.POST)
    @ResponseBody
    public R deleteFile(@RequestBody DeleteFileDTO deleteFileDto) {
        //逻辑和批量删除相同，批量删除就是多做了个循环
        UserBean sessionUserBean = (UserBean) SessionUtil.getSession();
        if (sessionUserBean == null) {
            throw new CommonException(ResultCodeEnum.NOT_LOGIN_ERROR);
        }
        userFileService.deleteUserFile(deleteFileDto.getUserFileId(), sessionUserBean.getUserId());
        return R.success(null);
    }


    /**
     * 通过文件类型选择文件
     * 该接口可以实现文件格式分类查看
     * @param fileType
     * @param currentPage
     * @param pageCount
     * @return
     */
    @RequestMapping(value = "/selectfilebyfiletype", method = RequestMethod.GET)
    @ResponseBody
    public R selectFileByFileType(@Parameter(description = "文件类型", required = true) int fileType,
                                                                      @Parameter(description = "当前页", required = true) long currentPage,
                                                                      @Parameter(description = "页面数量", required = true) long pageCount) {
        UserBean sessionUserBean = (UserBean) SessionUtil.getSession();
        if (sessionUserBean == null) {
            throw new NotLoginException();
        }
        long userId = sessionUserBean.getUserId();

        List<FileListVo> fileList;
        Long beginCount;
        if (pageCount == 0 || currentPage == 0) {
            beginCount = 0L;
            pageCount = 10L;
        } else {
            beginCount = (currentPage - 1) * pageCount;
        }

        Long total = 0L;
        if (fileType == com.qiwenshare.ufop.util.UFOPUtils.OTHER_TYPE) {

            List<String> arrList = new ArrayList<>();
            arrList.addAll(Arrays.asList(com.qiwenshare.ufop.util.UFOPUtils.DOC_FILE));
            arrList.addAll(Arrays.asList(com.qiwenshare.ufop.util.UFOPUtils.IMG_FILE));
            arrList.addAll(Arrays.asList(com.qiwenshare.ufop.util.UFOPUtils.VIDEO_FILE));
            arrList.addAll(Arrays.asList(com.qiwenshare.ufop.util.UFOPUtils.MUSIC_FILE));

            fileList = userFileService.selectFileNotInExtendNames(arrList,beginCount, pageCount, userId);
            total = userFileService.selectCountNotInExtendNames(arrList,beginCount, pageCount, userId);
        } else {
            fileList = userFileService.selectFileByExtendName(com.qiwenshare.ufop.util.UFOPUtils.getFileExtendsByType(fileType), beginCount, pageCount,userId);
            total = userFileService.selectCountByExtendName(com.qiwenshare.ufop.util.UFOPUtils.getFileExtendsByType(fileType), beginCount, pageCount,userId);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("list",fileList);
        map.put("total", total);
        return R.success(map);
    }




}
